<?php


namespace app\supplier\controller;


use app\erp\model\Dianzidb;
use app\erp\model\Orderdb;
use app\erp\model\UOrderdb;

class Dianzi extends Base
{
    public $post = array();

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $this->post = $request->param();
    }

    /**
     * Title("导出入库表")
     */
    public function rukubiao()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');

        $dianzidb = new Dianzidb();
        $dianzidb->param = $this->post;
        $dianzidb->param['apply_state'] = 1;
      //  $dianzidb->param['audit_yestoday'] = 'yes';
        $get_dianzi = $dianzidb->with(['cart.goods', 'orders'])->order('supplier_confirm_time asc')->select();
        $get_dianzi->append(['company_name']);
        $header_data = array(
            '军采单号',
            '入库时间',
            '订单类型',
            '订单时间',
            '收货地址',
            '收货人',
            '收货人电话',
            '客户',
            '供应商名称',
            '扣除点数',
            '商品信息',
            '型号',
            '税务大类',
            '税务编码',
            '开票名称',
            '规格型号',
            '单位',
            '数量',
            '销售单价',
            '销售金额',
            '采购单价(2位）',
            '采购总金额',
            '首付款',
            '快普货品编码',
            '快普品牌',
            '快普物料名称'
        );
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        $excel_data = [];
        if (!$get_dianzi->isEmpty()) {
            foreach ($get_dianzi as $key => $val) {
                foreach ($val['cart'] as $k => $v) {
                    $temp = [];
                    $temp[0] = "\t" . $val['out_order_no'];
                    $temp[1] = date('Y-m-d', $val['supplier_confirm_time']);
                    $temp[2] = $order_type_arr[$val['orders']['order_type']];
                    $temp[3] = $val['orders']['create_time'];
                    $temp[4] = $val['address'];
                    $temp[5] = $val['contact'];
                    $temp[6] = $val['phone'];
                    $temp[7] = '北京市泰龙吉贸易有限公司';
                    //$temp[8] = $val['company_name'];
                    $Uorderdb = new UOrderdb();
                    $hezuodanwei = $Uorderdb->where('out_order_no',$val['out_order_no'])->value('hezuodanwei');
                    if ($hezuodanwei == '自营2') {
                        $temp[8] = '南充多米科技有限责任公司';
                    } elseif ($hezuodanwei == '自营1') {
                        $temp[8] = '优士创新商业集团有限公司';
                    } elseif ($hezuodanwei == '优士') {
                        $temp[8] = '优士创新商业集团有限公司';
                    } elseif ($hezuodanwei == '卓品') {
                        $temp[8] = '广安卓品时代科技有限公司';
                    } elseif ($hezuodanwei == '自营A') {
                        $temp[8] = '华舰智能制造（山西）有限责任公司';
                    } elseif ($hezuodanwei == '自营B') {
                        $temp[8] = '华舰智能制造（山西）有限责任公司';
                    } else {
                        $temp[8] = $hezuodanwei;
                    }
                    $temp[9] = '96.6%';
                    $temp[10] = $v['goods']['goods_name'];
                    $temp[11] = $v['invoice_model'] ?: $v['goods']['invoice_model'];
                    $temp[12] = $v['product_area'] ?: $v['goods']['product_area'];
                    $temp[13] = "\t".($v['shuiwu_id'] ?: $v['goods']['shuiwu_id']);
                    $temp[14] = $v['product_firm'] ?: $v['goods']['product_firm'];
                    $temp[15] = $v['invoice_model'] ?: $v['goods']['invoice_model'];
                    $temp[16] = $v['goods_unit'] ?: $v['goods']['goods_unit'];
                    $temp[17] = $v['goods_num'];
                    $temp[18] = number_format(round($v['goods_sale_price'] * 0.97 * 100) / 100, 2, '.', '');
                  //  $all_money = 0;
                  //  foreach ($val['cart'] as $k1=>$v1){
                  //      $all_money += round($v1['goods_sale_price'] * 0.97 * 100) / 100 * $v1['goods_num'];
                  //  }
                  //  $temp[19] = $all_money;
                    $temp[19] = number_format(round($v['goods_sale_price'] * 0.97 * 100) / 100 * $v['goods_num'], 2, '.', '');
                    $temp[20] = number_format($v['goods_sale_price'] * 0.966, 2, '.', '');
                    //$temp[21] = $val['callect_money'];
                    $danjia = number_format(round($v['goods_sale_price'] * 96.6)/100,2,'.','');
                    $jine = number_format($danjia * $v['goods_num'],2,'.','');
                    $temp[21] = $jine;
                    $temp[22] = number_format($jine * 0.9, 2, '.', '');
                   // $temp[22] = $val['funded_money'];
                    $temp[23] = $v['goods']['goods_beizhu1'];
                    $temp[24] = $v['goods']['goods_beizhu2'];
                    $temp[25] = $v['goods']['goods_beizhu5'];
                    array_push($excel_data, $temp);
                }
            }
        }


        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '华舰入库表.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);


        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Dianzi/downExcel3', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    /**
     * Title("文件下载")
     */
    public function downExcel3($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 52) {
                $cell_value = chr(66) . chr($start + ($i - 52)) . '1';
                $cell_name = chr(66) . chr($start + ($i - 52));
            } elseif ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 52) {
                $cell_value = chr(66) . chr($start + ($i - 52));
            } elseif ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 10; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 10) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 10; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 10) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    /**
     * Title("导出采购合同")
     */
    public function caigou($file){
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allRow = $sheet->getHighestRow();
        $order_arr = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($order_arr, $out_order_no);
            }
        }
        //$base_url = 'http://tailongji.dixintong.com/';
        $add_file_flag = 0;
        if (count($order_arr) > 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->whereIn('out_order_no', $order_arr)->field('cght,out_order_no')->select();
            if (!$get_order->isEmpty()) {
                $zip_name = 'uploads/hetong/采购合同_'.date('YmdHis').'.zip';
                $zip = new \ZipArchive ();
                $res = $zip->open($zip_name, \ZipArchive::CREATE);
                if (!$res) {
                    halt('创建打包文件错误');
                }
                foreach ($get_order as $key => $val) {
                    if ($val ['cght']) {
                        $temp = explode('uploads/',$val['cght']);
                        if(count($temp) == 2){
                            $cgfp = 'uploads/'.$temp[1];
                        } else {
                            $cgfp = 'uploads/'.$val['cght'];
                        }
                        $ext = explode('.',$val['cght']);
                        $zip->addFile($cgfp, $val['out_order_no'] . '采购合同.'.end($ext));
                        $add_file_flag++;
                    }
                }

                $zip->close();
                if($add_file_flag == 0){
                    $this->layuiReturn('error', '没有可导出信息', -1);
                } else {
                    $this->layuiReturn('success', $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/' . $zip_name);
                }
            } else {
                $this->layuiReturn('error', '没有可导出信息2', -1);
            }
        } else {
            $this->layuiReturn('error', '没有可导出信息', -1);
        }
    }


    /**
     * Title("导出采购合同1")
     */
    public function caigou1($file){
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allRow = $sheet->getHighestRow();
        $order_arr = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($order_arr, $out_order_no);
            }
        }
        $add_file_flag = 0;
        //$base_url = 'http://tailongji.dixintong.com/';
        if (count($order_arr) > 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->whereIn('out_order_no', $order_arr)->field('cght1,out_order_no')->select();
            $uorderdb = new UOrderdb();
            if (!$get_order->isEmpty()) {
                $zip_name = 'uploads/hetong/采购合同1_'.date('YmdHis').'.zip';
                $zip = new \ZipArchive ();
                $res = $zip->open($zip_name, \ZipArchive::CREATE);
                if (!$res) {
                    halt('创建打包文件错误');
                }
                foreach ($get_order as $key => $val) {
                    if ($val ['cght1']) {
                        $temp = explode('uploads/',$val['cght1']);
                        $cgfp = 'uploads/'.$temp[1];
                        $ext = explode('.',$val['cght1']);
                        $zip->addFile($cgfp, $val['out_order_no'] . '采购合同1.'.end($ext));
                        $add_file_flag++;
                    } else {
                        $get_cght = $uorderdb->where('out_order_no',$val['out_order_no'])->value('cght');
                        $temp = explode('uploads/',$get_cght);
                        $cgfp = '/www/wwwroot/juncai_fen/uploads/'.$temp[1];
                        $ext = explode('.',$get_cght);
                        $zip->addFile($cgfp, $val['out_order_no'] . '采购合同1.'.end($ext));
                        $add_file_flag++;
                    }
                }

                $zip->close();
                if($add_file_flag == 0){
                    $this->layuiReturn('error', '没有可导出信息', -1);
                } else {
                    $this->layuiReturn('success', $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/' . $zip_name);
                }
            } else {
                $this->layuiReturn('error', '没有可导出信息2', -1);
            }
        } else {
            $this->layuiReturn('error', '没有可导出信息', -1);
        }
    }

}